const log4js = require('log4js');

log4js.configure({
    "appenders": {
        "access": {
            "type": "dateFile",
            "filename": "log/access.log",
            "pattern": "-yyyy-MM-dd"
        },
        "console": {
            "type": "console",
            // filename: "log/log"
        }
    },
    "categories": {
        "default": {
            "appenders": [
                "access"
            ],
            "level": "debug"
        },
        "console": {
            appenders: [
                'console'
            ],
            level: 'debug'
        }
    },
    pm2: true
});
let accessLogger = log4js.getLogger("access");
let consoleLogger = log4js.getLogger('console');

function formatAccessLog(ctx) {
    let log = `
${ctx.method} ${ctx.url}
ip: ${ctx.request.ip}\t
`;
    if (ctx.method.toUpperCase() === 'POST' || ctx.method.toUpperCase() === 'PUT') {
        log = `${log}body: ${ctx.request.body}\n`;
    }
    return log;
}

module.exports = async(ctx, next) => {
    let accessLog = formatAccessLog(ctx);
    accessLogger.info(accessLog);
    ctx.logger = consoleLogger;
    await next();
}